package com.hjq.demo.yuliao.dialog

import android.content.Context
import android.net.Uri
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.room.util.StringUtil
import com.bumptech.glide.Glide
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.hjq.base.BaseAdapter
import com.hjq.base.BaseDialog
import com.hjq.base.BaseVBActivity
import com.hjq.demo.R
import com.hjq.demo.aop.SingleClick
import com.hjq.demo.app.AppAdapter
import com.hjq.demo.app.vb.AppVbActivity
import com.hjq.demo.http.api.UpdateImageApi
import com.hjq.demo.http.glide.GlideApp
import com.hjq.demo.http.model.HttpData
import com.hjq.demo.ui.dialog.CommonDialog
import com.hjq.demo.yuliao.activity.ImageSelectVbActivity
import com.hjq.demo.yuliao.api.CreateRoomApi
import com.hjq.demo.yuliao.api.UploadImageApi
import com.hjq.http.EasyHttp
import com.hjq.http.lifecycle.ApplicationLifecycle
import com.hjq.http.listener.HttpCallback
import com.hjq.http.listener.OnHttpListener
import com.hjq.http.model.FileContentResolver
import com.hjq.toast.ToastUtils
import java.io.File
import java.lang.Exception

/**
 *
 * @author jiahe
 * 创建日期 2022/2/16
 * 描述 开语聊房弹窗
 *
 */
class OpenRoomDialog {
    class Builder(context: AppVbActivity<*>) : CommonRoomDialog.Builder<Builder>(context),
        View.OnLayoutChangeListener, Runnable {

        private val recyclerView: RecyclerView? by lazy { findViewById(R.id.rv_select_type) }
        private val recyclerViewBg: RecyclerView? by lazy { findViewById(R.id.rv_select_bg) }
        private val ivFm: ImageView? by lazy { findViewById(R.id.iv_fm) }
        private val setRoomTitle: EditText? by lazy { findViewById(R.id.set_room_title) }

        private val adapter: SelectAdapter
        private val adapterBg: SelectBgAdapter

        private var listener: OnListener<out Any>? = null

        private var mActivity: BaseVBActivity<*>? = null

        init {

            mActivity = context

            setCustomView(R.layout.dialog_open_voice_room)
            setGravity(Gravity.BOTTOM)
            recyclerView?.itemAnimator = null
            recyclerView?.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
            adapter = SelectAdapter(getContext())
            recyclerView?.adapter = adapter

            // 选择背景
            recyclerViewBg?.itemAnimator = null
            recyclerViewBg?.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
            adapterBg = SelectBgAdapter(getContext())
            recyclerViewBg?.adapter = adapterBg

            setOnClickListener(R.id.btn_create, R.id.iv_fm)
        }

        override fun dismiss() {
            super.dismiss()

            EasyHttp.cancel("upload_img")
            EasyHttp.cancel("create_room")
        }

        fun setList(vararg ids: Int): Builder = apply {
            val data: MutableList<Any> = ArrayList(ids.size)
            for (id in ids) {
                data.add(getString(id)!!)
            }
            setList(data)
        }

        fun setList(vararg data: String): Builder = apply {
            setList(mutableListOf(*data))
        }

        fun setList(data: MutableList<Any>): Builder = apply {
            adapter.setData(data)
            recyclerView?.addOnLayoutChangeListener(this)
        }

        fun setBgList(data: MutableList<Any>): Builder = apply {
            adapterBg.setData(data)
            recyclerViewBg?.addOnLayoutChangeListener(this)
        }

        /**
         * 设置默认选中的位置
         */
        fun setSelect(vararg positions: Int): Builder = apply {
            adapter.setSelect(*positions)
            adapterBg.setSelect(*positions)
        }

        /**
         * 设置最大选择数量
         */
        fun setMaxSelect(count: Int): Builder = apply {
            adapter.setMaxSelect(count)
            adapterBg.setMaxSelect(count)
        }

        /**
         * 设置最小选择数量
         */
        fun setMinSelect(count: Int): Builder = apply {
            adapter.setMinSelect(count)
            adapterBg.setMinSelect(count)
        }

        /**
         * 设置单选模式
         */
        fun setSingleSelect(): Builder = apply {
            adapter.setSingleSelect()
            adapterBg.setSingleSelect()
        }

        @Suppress("UNCHECKED_CAST")
        fun setListener(listener: OnListener<*>?): Builder = apply {
            this.listener = listener as OnListener<out Any>?
        }

        @SingleClick
        override fun onClick(view: View) {
            when (view.id) {
//                R.id.tv_ui_confirm -> {
//                    val data = adapter.getSelectSet()
//                    if (data.size >= adapter.getMinSelect()) {
//                        autoDismiss()
//                        listener?.onSelfSelected(getDialog(), data)
//                    } else {
//                        ToastUtils.show(String.format(getString(R.string.select_min_hint)!!, adapter.getMinSelect()))
//                    }
//                }
                R.id.tv_ui_cancel -> {
                    autoDismiss()
                    listener?.onCancel(getDialog())
                }
                R.id.btn_create -> {
                    if (avatarUrl == null) {
                        ToastUtils.show("请选择封面")
                        return
                    }
                    if (setRoomTitle?.text.toString().toString() == "") {
                        ToastUtils.show("请输入房间标题")
                        return
                    }
                    var mSelectType = ""
                    var mSelectBg = ""
                    val dataType = adapter.getSelectSet()
                    val dataBg = adapterBg.getSelectSet()
                    for ((key, value) in dataType) {
                        mSelectType = key.toString()
                    }
                    for ((key, value) in dataBg) {
                        mSelectBg = dataBg[key] as String
                    }

//                    if (data.size >= adapter.getMinSelect() && dataBg.size >= adapterBg.getMinSelect()) {
//                        autoDismiss()
//                        listener?.onSelfSelected(getDialog(), data, dataBg)
//                    } else {
//                        ToastUtils.show(String.format(getString(R.string.select_min_hint)!!, adapter.getMinSelect()))
//                    }

                    EasyHttp.post(ApplicationLifecycle())
                        .api(CreateRoomApi().apply {
                            this.is_public = mSelectType
                            this.room_background_url = mSelectBg
                            this.room_cover_url = avatarUrl.toString()
                            this.room_title = setRoomTitle?.text.toString().trim()
                        })
                        .tag("create_room")
                        .request(object : OnHttpListener<HttpData<Void?>> {
                            override fun onSucceed(data: HttpData<Void?>) {
                                ToastUtils.show(data.getMessage())
                                autoDismiss()
                                listener?.onSelfSelected(getDialog(), dataType, dataBg)
                            }

                            override fun onFail(e: Exception?) {

                            }
                        })
                }
                R.id.iv_fm -> {
                    selectFm()
                }
            }
        }

        /**
         * [View.OnLayoutChangeListener]
         */
        override fun onLayoutChange(
            v: View,
            left: Int,
            top: Int,
            right: Int,
            bottom: Int,
            oldLeft: Int,
            oldTop: Int,
            oldRight: Int,
            oldBottom: Int
        ) {
            recyclerView?.removeOnLayoutChangeListener(this)
            // 这里一定要加延迟，如果不加在 Android 9.0 上面会导致 setLayoutParams 无效
            post(this)
        }

        override fun run() {
            recyclerView?.let {
                val params = it.layoutParams ?: return
                val maxHeight = getScreenHeight() / 4 * 3
                if (it.height > maxHeight) {
                    if (params.height != maxHeight) {
                        params.height = maxHeight
                        it.layoutParams = params
                    }
                } else {
                    if (params.height != ViewGroup.LayoutParams.WRAP_CONTENT) {
                        params.height = ViewGroup.LayoutParams.WRAP_CONTENT
                        it.layoutParams = params
                    }
                }
            }
        }

        /**
         * 获取屏幕的高度
         */
        private fun getScreenHeight(): Int {
            val resources = getResources()
            val outMetrics = resources.displayMetrics
            return outMetrics.heightPixels
        }

        // 处理上传图片
        private var avatarUrl: Uri? = null
        private fun selectFm() {
            mActivity?.let {
                ImageSelectVbActivity.start(it, object : ImageSelectVbActivity.OnPhotoSelectListener {

                    override fun onSelected(data: MutableList<String>) {
                        // 裁剪头像
                        updateCropImage(File(data[0]), true)
                    }
                })
            }
        }

        /**
         * 上传图片
         */
        private fun updateCropImage(file: File, deleteFile: Boolean) {

            EasyHttp.post(ApplicationLifecycle())
                .api(UploadImageApi().apply {
                    this.file = file
                })
                .tag("upload_img")
                .request(object : OnHttpListener<HttpData<UploadImageApi.UploadImageResp?>> {
                    override fun onSucceed(data: HttpData<UploadImageApi.UploadImageResp?>) {
                        avatarUrl = Uri.parse(data.getData()?.file_url)
                        ivFm?.let {
                            GlideApp.with(getContext())
                                .load(data.getData()?.file_url)
                                .transform(MultiTransformation(CenterCrop()))
                                .into(it)
                        }
                        if (deleteFile) {
                            file.delete()
                        }
                    }

                    override fun onFail(e: Exception?) {

                    }
                })
        }
    }

    private class SelectAdapter(context: Context) : AppAdapter<Any>(context), BaseAdapter.OnItemClickListener {

        /** 最小选择数量 */
        private var minSelect = 1

        /** 最大选择数量 */
        private var maxSelect = Int.MAX_VALUE

        /** 选择对象集合 */
        private val selectSet: HashMap<Int, Any> = HashMap()

        init {
            setOnItemClickListener(this)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            return ViewHolder()
        }

        fun setSelect(vararg positions: Int) {
            for (position in positions) {
                selectSet[position] = getItem(position)
            }
            notifyDataSetChanged()
        }

        fun setMaxSelect(count: Int) {
            maxSelect = count
        }

        fun setMinSelect(count: Int) {
            minSelect = count
        }

        fun getMinSelect(): Int {
            return minSelect
        }

        fun setSingleSelect() {
            setMaxSelect(1)
            setMinSelect(1)
        }

        fun isSingleSelect(): Boolean {
            return maxSelect == 1 && minSelect == 1
        }

        fun getSelectSet(): HashMap<Int, Any> {
            return selectSet
        }

        /**
         * [BaseAdapter.OnItemClickListener]
         */
        override fun onItemClick(recyclerView: RecyclerView?, itemView: View?, position: Int) {
            if (selectSet.containsKey(position)) {
                // 当前必须不是单选模式才能取消选中
                if (!isSingleSelect()) {
                    selectSet.remove(position)
                    notifyItemChanged(position)
                }
            } else {
                if (maxSelect == 1) {
                    selectSet.clear()
                    notifyDataSetChanged()
                }
                if (selectSet.size < maxSelect) {
                    selectSet[position] = getItem(position)
                    notifyItemChanged(position)
                } else {
                    ToastUtils.show(String.format(getString(R.string.select_max_hint)!!, maxSelect))
                }
            }
        }

        private inner class ViewHolder : AppViewHolder(R.layout.select_room_type_item) {

            private val textView: TextView? by lazy { findViewById(R.id.tv_select_text) }
            private val checkBox: CheckBox? by lazy { findViewById(R.id.tv_select_checkbox) }

            override fun onBindView(position: Int) {
                textView?.text = getItem(position).toString()
                checkBox?.isChecked = selectSet.containsKey(position)
                if (maxSelect == 1) {
                    checkBox?.isClickable = false
                } else {
                    checkBox?.isEnabled = false
                }
            }
        }
    }

    private class SelectBgAdapter(context: Context) : AppAdapter<Any>(context), BaseAdapter.OnItemClickListener {

        /** 最小选择数量 */
        private var minSelect = 1

        /** 最大选择数量 */
        private var maxSelect = Int.MAX_VALUE

        /** 选择对象集合 */
        private val selectBgSet: HashMap<Int, Any> = HashMap()

        init {
            setOnItemClickListener(this)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            return ViewHolder()
        }

        fun setSelect(vararg positions: Int) {
            for (position in positions) {
                selectBgSet[position] = getItem(position)
            }
            notifyDataSetChanged()
        }

        fun setMaxSelect(count: Int) {
            maxSelect = count
        }

        fun setMinSelect(count: Int) {
            minSelect = count
        }

        fun getMinSelect(): Int {
            return minSelect
        }

        fun setSingleSelect() {
            setMaxSelect(1)
            setMinSelect(1)
        }

        fun isSingleSelect(): Boolean {
            return maxSelect == 1 && minSelect == 1
        }

        fun getSelectSet(): HashMap<Int, Any> {
            return selectBgSet
        }

        /**
         * [BaseAdapter.OnItemClickListener]
         */
        override fun onItemClick(recyclerView: RecyclerView?, itemView: View?, position: Int) {
            if (selectBgSet.containsKey(position)) {
                // 当前必须不是单选模式才能取消选中
                if (!isSingleSelect()) {
                    selectBgSet.remove(position)
                    notifyItemChanged(position)
                }
            } else {
                if (maxSelect == 1) {
                    selectBgSet.clear()
                    notifyDataSetChanged()
                }
                if (selectBgSet.size < maxSelect) {
                    selectBgSet[position] = getItem(position)
                    notifyItemChanged(position)
                } else {
                    ToastUtils.show(String.format(getString(R.string.select_max_hint)!!, maxSelect))
                }
            }
        }

        private inner class ViewHolder : AppViewHolder(R.layout.select_room_bg_item) {

            private val ivBg: ImageView? by lazy { findViewById(R.id.iv_select_bg) }
            private val checkBox: CheckBox? by lazy { findViewById(R.id.tv_select_checkbox) }

            override fun onBindView(position: Int) {

                ivBg?.let {
                    Glide.with(getContext())
                        .load(getItem(position))
                        .into(it)
                }

                checkBox?.isChecked = selectBgSet.containsKey(position)
                if (maxSelect == 1) {
                    checkBox?.isClickable = false
                } else {
                    checkBox?.isEnabled = false
                }
            }
        }
    }

    interface OnListener<T> {

        /**
         * 选择回调
         *
         * @param data              选择的位置和数据
         */
        @Suppress("UNCHECKED_CAST")
        fun onSelfSelected(dialog: BaseDialog?, data: HashMap<Int, out Any>, dataBg: HashMap<Int, out Any>) {
            onSelected(dialog, data as HashMap<Int, T>, dataBg as HashMap<Int, T>)
        }

        /**
         * 选择回调
         *
         * @param data              选择的位置和数据
         */
        fun onSelected(dialog: BaseDialog?, data: HashMap<Int, T>, dataBg: HashMap<Int, T>)

        /**
         * 取消回调
         */
        fun onCancel(dialog: BaseDialog?) {}
    }

}